package psnl.bingo.bgtool.model.dto;

import psnl.bingo.bgtool.model.util.ComputeLogic;
import psnl.bingo.bgtool.model.util.TDTool;

import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class TDFilter {
    public Boolean useLineLength;
    public String lineLengthOpt;
    public int lineLength;

    public Boolean useLineContent;
    public String lineContentOpt;
    public String lineContent;

    public List<TDCol> colCases;

    public List<Integer> repeatIndex;

    public Set<String> unRepeat = new HashSet<>();
    public Boolean useCaseFile;
    public Map<Integer, Integer> caseFileMatch;

    public Set<String> caseFT = new HashSet<>();

    /**
     * 判断是否保存该条数据
     * @param lineStr 数据行
     * @param lineItems 数据行按分隔符切分后的数组
     * @return
     * @throws Exception
     */
    public boolean saveLine(String lineStr, String[] lineItems) throws Exception {
        boolean logic;

        // 判断是否数据长度符合条件
        if(null != useLineLength) {
            logic = (boolean) ComputeLogic.class.getMethod(TDTool.getFilterRowLengthLogicType().get(lineLengthOpt), int.class, int.class)
                    .invoke(ComputeLogic.clObj, lineStr.length(), lineLength);

            logic = !(logic ^ useLineLength);

            if(!logic) {
                return false;
            }
        }

        // 判断是否数据内容符合条件
        if(null != useLineContent) {
            logic = (boolean) ComputeLogic.class.getMethod(TDTool.getFilterRowContentLogicType().get(lineContentOpt), String.class, String.class)
                    .invoke(ComputeLogic.clObj, lineStr, lineContent);

            logic = !(logic ^ useLineContent);
            if(!logic) {
                return false;
            }
        }

        // 判断列索引是否符合条件
        if(null != colCases && !colCases.isEmpty()) {
            for (TDCol col : colCases) {
                logic = (boolean) ComputeLogic.class.getMethod(TDTool.getFilterColumnLogicType().get(col.opt), String.class, String.class)
                        .invoke(ComputeLogic.clObj, lineItems[col.index], col.val);

                if(!logic) {
                    return false;
                }
            }
        }

        // 使用条件文件过滤
        if(null != useCaseFile) {
            String str = "";
            for (Integer index : caseFileMatch.keySet()) {
                str += lineItems[index];
            }

            logic = !(useCaseFile ^ caseFT.contains(str));

            if(!logic) {
                return false;
            }
        }

        // 指定列去重
        if(null != repeatIndex && !repeatIndex.isEmpty()) {
            String str = "";
            for (Integer index : repeatIndex) {
                str += lineItems[index];
            }
            if(unRepeat.contains(str)) {
                return false;
            }else {
                unRepeat.add(str);
            }
        }

        return true;
    }
}
